package xyz.cerberu.cet.global.domain;

import xyz.cerberu.cet.global.annotation.JsonFilter;
import xyz.cerberu.cet.global.filter.JacksonJsonFilter;
import xyz.cerberu.cet.global.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author β世界
 * Created on 9:22
 * @Description
 */
public class CustomerJsonSerializer {

    /**Json对象的mapper**/
    ObjectMapper mapper = new ObjectMapper();
    /** Jackson的字段过滤 **/
    JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();

    /**
     * @param clazz target type
     * @param include include fields
     * @param filter filter fields
     */
    public void filter(Class<?> clazz, String include, String filter) {
        if (clazz == null) {
            return;
        }
        if (StringUtils.isNotBlank(include)) {
            jacksonFilter.include(clazz, include.split(","));
        }
        if (StringUtils.isNotBlank(filter)) {
            jacksonFilter.filter(clazz, filter.split(","));
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    public String toJson(Object object) throws JsonProcessingException {
        mapper.setFilterProvider(jacksonFilter);
        return mapper.writeValueAsString(object);
    }

    public void filter(JsonFilter json) {
        this.filter(json.type(), json.include(), json.filter());
    }

}
